package code;

import code.ProductService;
import code.Product;
import java.io.*;
import java.net.*;
import java.util.List;

public class EStoreServer {
    private final ProductService productService = new ProductService();
    private final int port;

    public EStoreServer(int port) {
        this.port = port;
    }

    public void start() {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("服务器已启动，监听端口: " + port);
            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("收到客户端连接: " + clientSocket);
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (IOException e) {
            System.out.println("服务器启动失败: " + e.getMessage());
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            String request = (String) ois.readObject();
            System.out.println("收到客户端请求: " + request);

            switch (request) {
                case "GET_ALL_PRODUCTS":
                    List<Product> products = productService.getAllProducts();
                    oos.writeObject(products);
                    break;
                default:
                    oos.writeObject("未知请求");
            }
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("处理客户端请求失败: " + e.getMessage());
        } finally {
            try {
                clientSocket.close();
            } catch (IOException e) {
                System.out.println("关闭客户端连接失败: " + e.getMessage());
            }
        }
    }

    public static void main(String[] args) {
        new EStoreServer(8888).start();
    }
}